#include "qmythread.h"
#include <QMutex>
#include <QWaitCondition>
#include <QTime>

QThreadProducer::QThreadProducer(){

}

QThreadConsumer::QThreadConsumer(){

}

QMutex mutex;
QWaitCondition condition;
int seq = 0;  //序号
int diceValue;

void QThreadProducer::run(){
    m_stop = false;
    seq = 0;
    qsrand(QTime::currentTime().msec());
    while(!m_stop){
        mutex.lock();
        diceValue = qrand();
        diceValue = (diceValue % 6) + 1;
        seq++;
        mutex.unlock();
        condition.wakeAll();//唤醒所有线程，有新数据了
        msleep(500);
    }
}

void QThreadConsumer::run(){
    m_stop = false;
    while(!m_stop){
        mutex.lock();
        condition.wait(&mutex);//先解锁mutex，使其他线程可以使用mutex
        emit newValue(seq, diceValue);
        mutex.unlock();
    }
}

void QThreadProducer::stopThread(){
    m_stop = true;
}
